package com.alibaba.citrus.cr.order.open.api.facade.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.order.open.api.facade.common.until.CheckUtil;
import com.alibaba.citrus.cr.unified.inventory.contants.FeaturesKey;
import com.alibaba.citrus.cr.unified.inventory.facade.service.AllocateApplyOrderWriteServiceImpl;
import com.alibaba.citrus.cr.unified.inventory.repository.EsAllocateApplyOrderIndexRepository;
import com.alibaba.citrus.cr.unified.inventory.utils.NumberUtil;
import com.alibaba.citrus.cr.unified.inventory.utils.ToolUtil;
import com.alibaba.cloud.retail.store.api.service.CargoZoneQueryService;
import com.alibaba.cloud.retail.store.request.cargozone.QueryCargoZoneRequest;
import com.alibaba.cloud.retail.store.response.ResultPager;
import com.alibaba.cz.base.model.store.CargoZoneSDO;
import com.alibaba.cz.base.tool.FeatureUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.WarehouseInfo;
import com.epoch.app.bcorder.model.dto.WarehouseInfo;
import com.epoch.app.crunifiedinventory.api.allocateapplyorderread.service.AllocateApplyOrderReadService;
import com.epoch.app.crunifiedinventory.dto.request.QueryAllocateApplyOrderRequest;
import com.epoch.app.crunifiedinventory.dto.response.AllocateApplyOrderDetailDTO;
import com.epoch.app.crunifiedinventory.dto.response.AllocateApplyOrderGoodsDetailDTO;
import com.epoch.app.crunifiedinventory.dto.response.AllocateApplyOrderListDTO;
import com.epoch.app.crunifiedinventory.model.dto.AllocateApplyOrderQueryRequest;
import com.epoch.app.crunifiedinventory.model.dto.QueryEsAllocateApplyOrderIndexListRequest;
import com.epoch.app.crunifiedinventory.sdo.enums.AllocateOrderTypeEnum;
import com.epoch.app.mninventorycenter.model.dto.*;
import com.epoch.app.mninventorycenter.service.MnInventoryCenterService;
import com.epoch.app.mninventorycenter.transferforecastorderread.service.TransferForecastOrderReadService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TransferForecastOrderReadServiceImpl implements TransferForecastOrderReadService {

    Log log = com.alibaba.cz.base.tool.log.Log.getLogger(AllocateApplyOrderWriteServiceImpl.class);

    @Resource
    private AllocateApplyOrderReadService allocateApplyOrderReadService;

    @Resource
    private MnInventoryCenterService mnInventoryCenterService;

    @Resource
    private EsAllocateApplyOrderIndexRepository esAllocateApplyOrderIndexRepository;

    @DubboReference
    private CargoZoneQueryService cargoZoneQueryService;

    private static final String FROM_SYS_GROUP = "fromSys";
    private static final String BUSINESS_TYPE_GROUP = "businessType";
    private static final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";

    private static final String FIRST_SECOND = " 00:00:00";
    private static final String LAST_SECOND = " 23:59:59";

    @Override
    @FacadeInvoker(value = "根据调拨预报单单号查询")
    public Result<TransferForecastOrderQueryResponse> queryTransferForecastOrderByCode(
            TransferForecastOrderQueryRequest transferForecastOrderQueryRequest) {

        if(StringUtils.isBlank(transferForecastOrderQueryRequest.getTransferForecastOrderCode())){
            return Result.fail("10000","调拨预报单号不能为空");
        }
        if(transferForecastOrderQueryRequest.getTransferForecastOrderCode().length() >32){
            return Result.fail("10000","调拨预报单号字段长度大于32");
        }
        if(StringUtils.isBlank(transferForecastOrderQueryRequest.getFromSys())){
            return Result.fail("10000","系统来源不能为空");
        }
        if(transferForecastOrderQueryRequest.getFromSys().length()> 32){
            return Result.fail("10000","系统来源字段长度大于32");
        }
        if(StringUtils.isBlank(transferForecastOrderQueryRequest.getBusinessType())){
            return Result.fail("10000","业态号不能为空");
        }
        if(transferForecastOrderQueryRequest.getBusinessType().length() >32){
            return Result.fail("10000","业态号字段长度大于32");
        }
        if (!checkDictionary(FROM_SYS_GROUP,transferForecastOrderQueryRequest.getFromSys())){
            return Result.fail("10000","系统来源错误");
        }
        if (!checkDictionary(BUSINESS_TYPE_GROUP,transferForecastOrderQueryRequest.getBusinessType())){
            return Result.fail("10000","业态错误");
        }

        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(transferForecastOrderQueryRequest.getTransferForecastOrderCode());
        queryAllocateApplyOrderRequest.setBusinessType(transferForecastOrderQueryRequest.getBusinessType());
        queryAllocateApplyOrderRequest.setFromSys(transferForecastOrderQueryRequest.getFromSys());
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResult = allocateApplyOrderReadService.queryAllocateApplyOrder(queryAllocateApplyOrderRequest);

        AllocateApplyOrderDetailDTO result = allocateApplyOrderDetailDTOResult.getResult();
        if(result == null){
            return Result.success(null);
        }
        //获取仓库
        List<String> warechouseIds = new ArrayList<>();
        if (StrUtil.isNotBlank(result.getReceiveWarehouseId())){
            warechouseIds.add(result.getReceiveWarehouseId());
        }
        if (StrUtil.isNotBlank(result.getShipWarehouseId())){
            warechouseIds.add(result.getShipWarehouseId());
        }
        QueryWarehouseByIdApiRequest request = new QueryWarehouseByIdApiRequest();
        request.setWarehouseIds(warechouseIds);
        Result<List<WarehouseQueryResponse>> queryWarehouseByIdApi = mnInventoryCenterService.queryWarehouseByIdApi(request);
        Map<String,String> idCodeMap = new HashMap<>();
        Map<String,String> idNameMap = new HashMap<>();
        if (CollectionUtil.isNotEmpty(queryWarehouseByIdApi.getResult())){
            idCodeMap = queryWarehouseByIdApi.getResult().stream().collect(Collectors.toMap(WarehouseQueryResponse::getId,WarehouseQueryResponse::getCode));
            idNameMap = queryWarehouseByIdApi.getResult().stream().collect(Collectors.toMap(WarehouseQueryResponse::getId,WarehouseQueryResponse::getName));
        }

        TransferForecastOrderQueryResponse transferForecastOrderQueryResponse = new TransferForecastOrderQueryResponse();
        transferForecastOrderQueryResponse.setFromSys(result.getFromSys());
        transferForecastOrderQueryResponse.setBusinessType(result.getBusinessType());
        transferForecastOrderQueryResponse.setTransferForecastOrderCode(result.getCode());
        transferForecastOrderQueryResponse.setTransferForecastOrderType(result.getType());
        /*transferForecastOrderQueryResponse.setReceiveLogicWareId(result.getReceiveWarehouseId());
        transferForecastOrderQueryResponse.setReceiveLogicWareName(result.getReceiveWarehouseName());
        transferForecastOrderQueryResponse.setDeliveryLogicWareId(result.getShipWarehouseId());
        transferForecastOrderQueryResponse.setDeliveryLogicWareName(result.getShipWarehouseName());*/
        transferForecastOrderQueryResponse.setReceiveLogicWareCode(idCodeMap.get(result.getReceiveWarehouseId()));
        transferForecastOrderQueryResponse.setReceiveLogicWareName(idNameMap.get(result.getReceiveWarehouseId()));
        transferForecastOrderQueryResponse.setDeliveryLogicWareCode(idCodeMap.get(result.getShipWarehouseId()));
        transferForecastOrderQueryResponse.setDeliveryLogicWareName(idNameMap.get(result.getShipWarehouseId()));
        transferForecastOrderQueryResponse.setOrderDate(result.getOrderTime());
        transferForecastOrderQueryResponse.setEffectiveDate(result.getTakeEffectTime());
        transferForecastOrderQueryResponse.setInvalidDate(result.getInvalidDate());
        transferForecastOrderQueryResponse.setExpectedDeliveryDate(result.getHopeDeliveryTime());
        transferForecastOrderQueryResponse.setShipMethodCode(result.getShipMethod());
        transferForecastOrderQueryResponse.setHeadquartersOrganizationCode(result.getHeadquartersOrganizationCode());
        transferForecastOrderQueryResponse.setHeadquartersChannelCode(result.getHeadquartersChannelCode());
        transferForecastOrderQueryResponse.setHeadRemark(result.getRemark());
        transferForecastOrderQueryResponse.setCreator(result.getCreatorName());
        transferForecastOrderQueryResponse.setGmtCreate(result.getGmtCreate());

        List<AllocateApplyOrderGoodsDetailDTO> list = result.getList();
        if(CollectionUtil.isNotEmpty(list)){
            List<TransferForecastOrderQueryDetailResponse> collect = list.stream().map(x -> {
                TransferForecastOrderQueryDetailResponse transferForecastOrderQueryDetailResponse = new TransferForecastOrderQueryDetailResponse();
                transferForecastOrderQueryDetailResponse.setDetailNo(x.getLineNo());
                transferForecastOrderQueryDetailResponse.setGoodsCode(x.getScItemId());
                transferForecastOrderQueryDetailResponse.setGoodsName(x.getTitle());
                transferForecastOrderQueryDetailResponse.setQuantity(x.getApplyQuantity());
                transferForecastOrderQueryDetailResponse.setLineRemark(x.getRemark());
//                transferForecastOrderQueryDetailResponse.setCreator("");
//                transferForecastOrderQueryDetailResponse.setGmtCreate(null);
//                transferForecastOrderQueryDetailResponse.setModifier("");
//                transferForecastOrderQueryDetailResponse.setGmtModified(null);
                return transferForecastOrderQueryDetailResponse;
            }).collect(Collectors.toList());
            transferForecastOrderQueryResponse.setTransferForecastOrderQueryDetailResponseList(collect);
        }
        return Result.success(transferForecastOrderQueryResponse);
    }

    @Override
    @FacadeInvoker(value = "调拨预报单列表查询")
    public Result<List<TransferForecastOrderQueryListResponse>> queryTransferForecastOrderList(
            TransferForecastOrderQueryListRequest transferForecastOrderQueryListRequest) {

        String message = checkFromSysAndBusinessType(transferForecastOrderQueryListRequest);

        if(message !=null){
            return Result.fail("10000",message);
        }
        AllocateApplyOrderQueryRequest allocateApplyOrderQueryRequest = new AllocateApplyOrderQueryRequest();
        allocateApplyOrderQueryRequest.setCode(transferForecastOrderQueryListRequest.getTransferForecastOrderCode());
        if(transferForecastOrderQueryListRequest.getTransferForecastOrderType() !=null && transferForecastOrderQueryListRequest.getTransferForecastOrderType().length() > 0){
            allocateApplyOrderQueryRequest.setType(Collections.singletonList(Integer.parseInt(transferForecastOrderQueryListRequest.getTransferForecastOrderType())));
        }
//        if(transferForecastOrderQueryListRequest.getGoodsCode() !=null){
//            List<ScItemResponse> scItemInfoList = getScItemInfoList(Collections.singletonList(transferForecastOrderQueryListRequest.getGoodsCode()));
//            if(CollectionUtil.isEmpty(scItemInfoList)){
//                Result<List<TransferForecastOrderQueryListResponse>> success = Result.success(null);
//                success.setTotal(0);
//                return success;
//            }
//            allocateApplyOrderQueryRequest.setScItemId(scItemInfoList.get(0).getScItemId());
//        }
        allocateApplyOrderQueryRequest.setTitle(transferForecastOrderQueryListRequest.getGoodsCode());
        if(StringUtils.isNotEmpty(transferForecastOrderQueryListRequest.getReceiveLogicWarehouseCode())){
            WarehouseQueryResponse warehouseInfo = getWarehouseInfo(transferForecastOrderQueryListRequest.getReceiveLogicWarehouseCode());
            if(warehouseInfo == null){
                Result<List<TransferForecastOrderQueryListResponse>> success = Result.success(null);
                success.setTotal(0);
                return success;
            }
            allocateApplyOrderQueryRequest.setReceiveWarehouseId(Integer.parseInt(warehouseInfo.getId()));
        }

        if(StringUtils.isNotEmpty(transferForecastOrderQueryListRequest.getGmtCreateStart())){
            allocateApplyOrderQueryRequest.setGmtCreateStart(CheckUtil.strToDate(transferForecastOrderQueryListRequest.getGmtCreateStart()));
        }
        if(StringUtils.isNotEmpty(transferForecastOrderQueryListRequest.getGmtCreateEnd())){
            allocateApplyOrderQueryRequest.setGmtCreateEnd(CheckUtil.strToDate(transferForecastOrderQueryListRequest.getGmtCreateEnd()));
        }
        allocateApplyOrderQueryRequest.setCreator(transferForecastOrderQueryListRequest.getCreator());
        allocateApplyOrderQueryRequest.setFromSys(transferForecastOrderQueryListRequest.getFromSys());
        allocateApplyOrderQueryRequest.setBusinessType(transferForecastOrderQueryListRequest.getBusinessType());
        allocateApplyOrderQueryRequest.setPage(transferForecastOrderQueryListRequest.getPage());
        allocateApplyOrderQueryRequest.setSize(transferForecastOrderQueryListRequest.getSize());
        List<Integer> list = new ArrayList<>();
        list.add(99);//查询全部
        allocateApplyOrderQueryRequest.setLineStatus(list);
        Result<List<AllocateApplyOrderListDTO>> listResult =
                allocateApplyOrderReadService.queryNoAuthAllocateApplyOrderList(allocateApplyOrderQueryRequest);
        List<AllocateApplyOrderListDTO> result = listResult.getResult();
        if(CollectionUtil.isEmpty(result)){
            return Result.success(null);
        }

        List<TransferForecastOrderQueryListResponse> collect = result.stream().map(x -> {
            TransferForecastOrderQueryListResponse response = new TransferForecastOrderQueryListResponse();
            response.setFromSys(x.getFromSys());
            response.setBusinessType(x.getBusinessType());
            response.setTransferForecastOrderCode(x.getCode());
            if(x.getLineNo() !=null){
                response.setDetailNo(String.valueOf(x.getLineNo()));
            }
            response.setTransferForecastOrderType(x.getType());
            response.setDeliveryLogicWarehouseName(x.getShipWarehouseName());
            response.setReceiveLogicWarehouseName(x.getReceiveWarehouseName());
            response.setOrderDate(x.getOrderTime());
            response.setEffectiveDate(x.getTakeEffectTime());
            response.setInvalidDate(x.getInvalidDate());
            response.setExpectedDeliveryDate(x.getHopeDeliveryTime());
            response.setHeadRemark(x.getRemark());
            response.setGoodsCode(x.getScItemId());
            response.setGoodsName(x.getTitle());
            response.setQuantity(x.getApplyQuantity());
            response.setDetailRemark(x.getItemRemark());
            return response;
        }).collect(Collectors.toList());
        Result<List<TransferForecastOrderQueryListResponse>> success = Result.success(collect);
        success.setTotal(listResult.getTotal());
        return success;
    }
    private String checkFromSysAndBusinessType( TransferForecastOrderQueryListRequest req){
        if (checkFieldLength(req.getTransferForecastOrderCode())) {
            return "调拨预报单号字段长度大于32";
        }
        if(checkFieldLength(req.getTransferForecastOrderType())){
            return "调拨预报订单订单类型字段长度大于32";
        }
        if(StringUtils.isNotEmpty(req.getTransferForecastOrderType())){
            if(req.getTransferForecastOrderType().length() > 9){
                return "调拨预报订单订单类型字段长度大于9";
            }
            if(!StringUtils.isNumeric(req.getTransferForecastOrderType())){
                return "调拨预报单类型非法";
            }
            AllocateOrderTypeEnum allocateOrderTypeEnumType = CheckUtil.getAllocateOrderTypeEnumType(Integer.valueOf(req.getTransferForecastOrderType()));
            if(allocateOrderTypeEnumType == null){
                return "调拨单类型不存在";
            }
        }
        if (checkFieldLength(req.getGoodsCode())) {
            return "货品编码字段长度大于32";
        }
        if (checkFieldLength(req.getDeliveryLogicWarehouseCode())) {
            return "发货逻辑仓库编码字段长度大于32";
        }
        if (checkFieldLength(req.getReceiveLogicWarehouseCode())) {
            return "收货逻辑仓库编码字段长度大于32";
        }
        if (checkFieldLength(req.getCreator())) {
            return "创建人字段长度大于32";
        }
        if (StringUtils.isBlank(req.getBusinessType())) {
            return "业态不能为空";
        }
        if(req.getBusinessType().length()> 32){
            return "业态字段长度大于32";
        }
        if(StringUtils.isBlank(req.getFromSys())){
            return "系统来源不能为空";
        }
        if(req.getFromSys().length()> 32){
            return "系统来源字段长度大于32";
        }
        if(StringUtils.isNotEmpty(req.getGmtCreateStart())){
            if(req.getGmtCreateStart().length() != 19
                    || !CheckUtil.isLegalDate(req.getGmtCreateStart())){
                return "创建时间-开始格式应为yyyy-MM-dd HH:mm:SS";
            }
        }
        if(StringUtils.isNotEmpty(req.getGmtCreateEnd())){
            if(req.getGmtCreateEnd().length() != 19
                    || !CheckUtil.isLegalDate(req.getGmtCreateEnd())){
                return "创建时间-结束格式应为yyyy-MM-dd HH:mm:SS";
            }
        }
        if(req.getPage() != null){
            if(req.getPage() >9999){
                return "page不能大于9999";
            }
        }
        if(req.getSize() != null){
            if(req.getSize() >100){
                return "size不能大于100";
            }
        }

        if (!checkDictionary(FROM_SYS_GROUP,req.getFromSys())){
            return "系统来源错误";
        }
        if (!checkDictionary(BUSINESS_TYPE_GROUP,req.getBusinessType())){
            return "业态错误";
        }

        return null;
    }

    private boolean checkFieldLength(String field) {
        if (Objects.nonNull(field) && field.length() > 32) {
            return true;
        }
        return false;
    }
    /**
     * 校验字典
     * @param group group
     * @param code code
     * @return boolean
     */
    private boolean checkDictionary(String group, String code) {
        DictionaryQueryRequest request = new DictionaryQueryRequest();
        request.setGroup(group);
        Result<List<DictionaryResponse>> result = mnInventoryCenterService.queryDictionaryDataListApi(request);
        Set<String> businessTypeSet = result.getResult().stream()
                .map(DictionaryResponse::getCode)
                .collect(Collectors.toSet());
        return businessTypeSet.contains(code);
    }

    /**
     * 通过货品外部编码（goodsCode）查询货品详情goodsInfo(scItem)  getScItemInfoList
     */
    public List<ScItemResponse> getScItemInfoList(List<String> outerIdList){
        ScItemSearchReqAbilityDTO scItemSearchReqAbilityDTO1 = new ScItemSearchReqAbilityDTO();
        scItemSearchReqAbilityDTO1.setOuterIdList(outerIdList);
        Result<List<ScItemResponse>> listResult = mnInventoryCenterService.searchScItemFromDbList(scItemSearchReqAbilityDTO1);

        return listResult.getResult();
    }

    public List<ScItemResponse> getScItemInfoListByIdList(List<String> idList){
        ScItemSearchReqAbilityDTO scItemSearchReqAbilityDTO1 = new ScItemSearchReqAbilityDTO();
        scItemSearchReqAbilityDTO1.setScItemIds(idList);
        Result<List<ScItemResponse>> listResult = mnInventoryCenterService.searchScItemFromDbList(scItemSearchReqAbilityDTO1);

        return listResult.getResult();
    }

    /**
     * 根据
     * @param warehouseCode code
     * @return WarehouseQueryResponse
     */
    private WarehouseQueryResponse getWarehouseInfo(String warehouseCode){
        WarehouseQueryRequest warehouseQueryRequest = new WarehouseQueryRequest();
        warehouseQueryRequest.setMerchantCode("mengniu");
        warehouseQueryRequest.setCode(warehouseCode);
        Result<WarehouseQueryResponse> warehouseResult = mnInventoryCenterService.queryWarehoseByCodeApi(warehouseQueryRequest);
        if(warehouseResult.getResult() == null){
            return null;
        }
        if(warehouseResult.getResult().getId() == null){
            return null;
        }
        return warehouseResult.getResult();
    }

    @Override
    @FacadeInvoker(value = "调拨预报单列表查询V2")
    public Result<List<AllocateApplyOrderQueryResponse>> queryNoAuthAllocateApplyOrderListV2(AllocateApplyOrderListQueryRequest request) {
        QueryEsAllocateApplyOrderIndexListRequest queryEsAllocateApplyOrderIndexListRequest = new QueryEsAllocateApplyOrderIndexListRequest();
        queryEsAllocateApplyOrderIndexListRequest.setSize(request.getSize());
        queryEsAllocateApplyOrderIndexListRequest.setPage(request.getPage());
        queryEsAllocateApplyOrderIndexListRequest.setStart(request.getStart());
        queryEsAllocateApplyOrderIndexListRequest.setLimit(request.getLimit());
        queryEsAllocateApplyOrderIndexListRequest.setFromSys(request.getFromSys());

        queryEsAllocateApplyOrderIndexListRequest.setCode(request.getAllocateApplyOrderCode());
        queryEsAllocateApplyOrderIndexListRequest.setOutAllocateApplyOrderId(request.getOutAllocateApplyOrderId());
        queryEsAllocateApplyOrderIndexListRequest.setMainStatus(request.getStatus());
        queryEsAllocateApplyOrderIndexListRequest.setLineStatus(request.getLineStatus());
        queryEsAllocateApplyOrderIndexListRequest.setReceiveWarehouseId(request.getReceiveWarehouseId());

        queryEsAllocateApplyOrderIndexListRequest.setGoodsCode(request.getGoodsCode());
        if (StringUtils.isNotBlank(request.getGmtCreateStart())) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_PATTERN);
            String gmtCreateStart = request.getGmtCreateStart();
            try {
                gmtCreateStart = gmtCreateStart.concat(FIRST_SECOND);
                Date parsed = simpleDateFormat.parse(gmtCreateStart);
                queryEsAllocateApplyOrderIndexListRequest.setGmtCreateStart(parsed.getTime());
            } catch (ParseException e) {
                log.error("TransferForecastOrderReadServiceImpl|queryNoAuthAllocateApplyOrderListV2|error|gmtCreateParseError|gmtCreate={}|", gmtCreateStart, e);
            }
        }
        if (StringUtils.isNotBlank(request.getGmtCreateEnd())) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_PATTERN);
            String gmtCreateEnd = request.getGmtCreateEnd();
            try {
                gmtCreateEnd = gmtCreateEnd.concat(LAST_SECOND);
                Date parsed = simpleDateFormat.parse(gmtCreateEnd);
                queryEsAllocateApplyOrderIndexListRequest.setGmtCreateEnd(parsed.getTime());
            } catch (ParseException e) {
                log.error("TransferForecastOrderReadServiceImpl|queryNoAuthAllocateApplyOrderListV2|error|gmtCreateParseError|gmtCreate={}|", gmtCreateEnd, e);
            }
        }
        queryEsAllocateApplyOrderIndexListRequest.setCreator(request.getCreator());

        if (StringUtils.isNotBlank(request.getGmtModifiedStart())) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_PATTERN);
            String gmtModifiedStart = request.getGmtModifiedStart();
            try {
                gmtModifiedStart = gmtModifiedStart.concat(FIRST_SECOND);
                Date parsed = simpleDateFormat.parse(gmtModifiedStart);
                queryEsAllocateApplyOrderIndexListRequest.setGmtModifiedStart(parsed.getTime());
            } catch (ParseException e) {
                log.error("TransferForecastOrderReadServiceImpl|queryNoAuthAllocateApplyOrderListV2|error|gmtCreateParseError|gmtCreate={}|", gmtModifiedStart, e);
            }
        }

        if (StringUtils.isNotBlank(request.getGmtModifiedEnd())) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_PATTERN);
            String gmtModifiedEnd = request.getGmtModifiedEnd();
            try {
                gmtModifiedEnd = gmtModifiedEnd.concat(LAST_SECOND);
                Date parsed = simpleDateFormat.parse(gmtModifiedEnd);
                queryEsAllocateApplyOrderIndexListRequest.setGmtModifiedEnd(parsed.getTime());
            } catch (ParseException e) {
                log.error("TransferForecastOrderReadServiceImpl|queryNoAuthAllocateApplyOrderListV2|error|gmtCreateParseError|gmtCreate={}|", gmtModifiedEnd, e);
            }
        }

        if (StringUtils.isNotBlank(request.getTakeEffectTimeStart())) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_PATTERN);
            String takeEffectTimeStart = request.getTakeEffectTimeStart();
            try {
                takeEffectTimeStart = takeEffectTimeStart.concat(FIRST_SECOND);
                Date parsed = simpleDateFormat.parse(takeEffectTimeStart);
                queryEsAllocateApplyOrderIndexListRequest.setTakeEffectTimeStart(parsed.getTime());
            } catch (ParseException e) {
                log.error("TransferForecastOrderReadServiceImpl|queryNoAuthAllocateApplyOrderListV2|error|gmtCreateParseError|gmtCreate={}|", takeEffectTimeStart, e);
            }
        }

        if (StringUtils.isNotBlank(request.getTakeEffectTimeEnd())) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_PATTERN);
            String takeEffectTimeEnd = request.getTakeEffectTimeEnd();
            try {
                takeEffectTimeEnd = takeEffectTimeEnd.concat(LAST_SECOND);
                Date parsed = simpleDateFormat.parse(takeEffectTimeEnd);
                queryEsAllocateApplyOrderIndexListRequest.setTakeEffectTimeEnd(parsed.getTime());
            } catch (ParseException e) {
                log.error("TransferForecastOrderReadServiceImpl|queryNoAuthAllocateApplyOrderListV2|error|gmtCreateParseError|gmtCreate={}|", takeEffectTimeEnd, e);
            }
        }

        if (StringUtils.isNotBlank(request.getExpectedDeliveryDateStart())) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_PATTERN);
            String expectedDeliveryDateStart = request.getExpectedDeliveryDateStart();
            try {
                expectedDeliveryDateStart = expectedDeliveryDateStart.concat(FIRST_SECOND);
                Date parsed = simpleDateFormat.parse(expectedDeliveryDateStart);
                queryEsAllocateApplyOrderIndexListRequest.setHopeDeliveryTimeStart(parsed.getTime());
            } catch (ParseException e) {
                log.error("TransferForecastOrderReadServiceImpl|queryNoAuthAllocateApplyOrderListV2|error|gmtCreateParseError|gmtCreate={}|", expectedDeliveryDateStart, e);
            }
        }

        if (StringUtils.isNotBlank(request.getExpectedDeliveryDateEnd())) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_PATTERN);
            String expectedDeliveryDateEnd = request.getExpectedDeliveryDateEnd();
            try {
                expectedDeliveryDateEnd = expectedDeliveryDateEnd.concat(LAST_SECOND);
                Date parsed = simpleDateFormat.parse(expectedDeliveryDateEnd);
                queryEsAllocateApplyOrderIndexListRequest.setHopeDeliveryTimeEnd(parsed.getTime());
            } catch (ParseException e) {
                log.error("TransferForecastOrderReadServiceImpl|queryNoAuthAllocateApplyOrderListV2|error|ExpectedDeliveryParseError|gmtCreate={}|", expectedDeliveryDateEnd, e);
            }
        }

        queryEsAllocateApplyOrderIndexListRequest.setUpdater(request.getUpdator());
        queryEsAllocateApplyOrderIndexListRequest.setRemark(request.getRemark());
        queryEsAllocateApplyOrderIndexListRequest.setLineRemark(request.getLineRemark());

        queryEsAllocateApplyOrderIndexListRequest.setShipWarehouseId(request.getDeliveryWarehouseId());
        queryEsAllocateApplyOrderIndexListRequest.setReceiveContacts(request.getContact());
        queryEsAllocateApplyOrderIndexListRequest.setReceivePhone(request.getContactPhone());
        queryEsAllocateApplyOrderIndexListRequest.setOrderTag(request.getOrderTagList());
        queryEsAllocateApplyOrderIndexListRequest.setBizUnit(request.getBizUnit());
        if (CollectionUtils.isNotEmpty(request.getDeliveryWarehouseIdList())){
            queryEsAllocateApplyOrderIndexListRequest.setShipWarehouseIdList(request.getDeliveryWarehouseIdList());
        }
        if (CollectionUtils.isNotEmpty(request.getReceiveWarehouseIdList())){
            queryEsAllocateApplyOrderIndexListRequest.setReceiveWarehouseIdList(request.getReceiveWarehouseIdList());
        }
        Result<List<AllocateApplyOrderListDTO>> listResult = esAllocateApplyOrderIndexRepository.queryEsAllocateApplyOrderIndexListV2(queryEsAllocateApplyOrderIndexListRequest);
        log.info("TransferForecastOrderReadServiceImpl|queryNoAuthAllocateApplyOrderListV2|queryES|request={}|result={}|", JSON.toJSONString(queryEsAllocateApplyOrderIndexListRequest), JSON.toJSONString(listResult));

        if(CollectionUtil.isEmpty(listResult.getResult())){
            Result success = Result.success(null);
            success.setTotal(0);
            return success;
        }
        DictionaryQueryRequest dictionaryQueryRequest = new DictionaryQueryRequest();
        dictionaryQueryRequest.setGroup("allocateApplyOrderTag");
        Result<List<DictionaryResponse>> dictionaryResult = mnInventoryCenterService.queryDictionaryDataListApi(dictionaryQueryRequest);
        Map<String,String> orderTagMap = dictionaryResult.getResult().stream().collect(Collectors.toMap(DictionaryResponse::getCode, DictionaryResponse::getName, (a, b) -> a));
        dictionaryQueryRequest.setGroup("businessUnitCode");
        Result<List<DictionaryResponse>> bizUnitResult = mnInventoryCenterService.queryDictionaryDataListApi(dictionaryQueryRequest);
        Map<String, String> bizUnitMap = bizUnitResult.getResult().stream().collect(Collectors.toMap(DictionaryResponse::getCode, DictionaryResponse::getName, (a, b) -> a));
        List<AllocateApplyOrderListDTO> result = listResult.getResult();
        // 转换
        List<AllocateApplyOrderQueryResponse> responseList = result.stream().map(x -> {
            AllocateApplyOrderQueryResponse response = new AllocateApplyOrderQueryResponse();

            response.setTransferForecastOrderCode(x.getCode());

            response.setGoodsId(x.getGoodsId());
            response.setGoodsCode(x.getScItemId());
            response.setGoodsName(x.getTitle());
            response.setLineNo(x.getLineNo() == null ? null : x.getLineNo().toString());
            // SAP预报单号
            response.setBorrowGoodsTransferOrderCode(x.getOutAllocateApplyOrderId());
            response.setReceiveWarehouseId(x.getReceiveWarehouseId() == null ? null : x.getReceiveWarehouseId().toString());
            response.setReceiveWarehouseCode(null);
            response.setReceiveWarehouseName(x.getReceiveWarehouseName());
            response.setShipWarehouseId(x.getShipWarehouseId());
            response.setShipWarehouseCode(null);
            response.setShipWarehouseName(x.getShipWarehouseName());
            response.setStatus(x.getStatus());
            response.setStatusName(x.getStatusName());
            response.setLineStatus(x.getLineStatus() == null ? null : Integer.parseInt(x.getLineStatus()));
            response.setLineStatusName(x.getLineStatusName());
            response.setForecastAmount(x.getApplyQuantity() == null ? null : x.getApplyQuantity().toString());
            response.setReplyAmount(x.getReplyQuantity() == null ? null : x.getReplyQuantity().toString());
            response.setPendingReplyAmount(x.getNoReplyQuantity() == null ? null : x.getNoReplyQuantity().toString());
            response.setConfirmedAmount(x.getConfirmQuantity() == null ? null : x.getConfirmQuantity().toString());
            response.setOutboundAmount(x.getDeliverQuantity() == null ? null : x.getDeliverQuantity().toString());
            String bizFeature = x.getBizFeature();
            Map<String, String> bizFeatureMap = FeatureUtil.fromString(bizFeature);
            String cumulativeDeliveryQuantity = bizFeatureMap.get(FeaturesKey.CUMULATIVE_DELIVERY_QUANTITY);
            String cumulativeReceivedQuantity = bizFeatureMap.get(FeaturesKey.CUMULATIVE_RECEIVED_QUANTITY);
            String cumulativeCompleteQuantity = bizFeatureMap.get(FeaturesKey.CUMULATIVE_COMPLETE_QUANTITY);

            // 未走量调拨单中已经确认但未发货的数量，【确认量-发货量】
            if (x.getConfirmQuantity() != null) {
//                int notShipped = x.getConfirmQuantity() - x.getDeliverQuantity();
                String notShippedAmount = NumberUtil.subtract(x.getConfirmQuantity().toString(),cumulativeDeliveryQuantity);
                response.setNotShippedAmount(notShippedAmount);
            }

            // 在途量 features中的【“累计已发货数量”-“累计已收货数量”】
            /**
             * 货场仓 收货 [ 累计已出库数量 ] - 累计已完成数量 ]
             * 非货场 仓收货 ．[累计已出库数量] - [累计已收货数量 ]
             */
            if (ToolUtil.isTrainOrSea(x.getShipMethod())){
                response.setInTransitAmount(NumberUtil.subtract(cumulativeDeliveryQuantity,cumulativeCompleteQuantity));
            }else {
                response.setInTransitAmount(NumberUtil.subtract(cumulativeDeliveryQuantity,cumulativeReceivedQuantity));
            }
//            if (x.getCumulativeDeliveryQuantity() != null && x.getCumulativeReceiveQuantity() != null) {
//                if (StringUtils.isNumeric(x.getCumulativeDeliveryQuantity() ) && StringUtils.isNumeric(x.getCumulativeReceiveQuantity())) {
//                    int inTransit = Integer.parseInt(x.getCumulativeDeliveryQuantity()) - Integer.parseInt(x.getCumulativeReceiveQuantity());
//                    response.setInTransitAmount(Integer.toString(inTransit));
//                }
//            }
//            response.setInTransitAmount(x.getDeliverQuantity() == null || x. getArrivalQuantity() == null ? null : String.valueOf(x.getDeliverQuantity() - x.getArrivalQuantity()));
            response.setDeliveryAmount(x.getCumulativeDeliveryQuantity() == null ? null : x.getCumulativeDeliveryQuantity().toString());

            // 货场量 铁海：调拨预报单features中的【“累计已收货数量”-“累计已提货数量”】
            if ("2".equals(x.getShipMethod()) || "3".equals(x.getShipMethod())) {
                if (x.getCumulativeReceiveQuantity() != null && x.getCumulativePickQuantity() != null) {
                    if (StringUtils.isNumeric(x.getCumulativeReceiveQuantity() ) && StringUtils.isNumeric(x.getCumulativePickQuantity())) {
                        int yard = Integer.parseInt(x.getCumulativeReceiveQuantity()) - Integer.parseInt(x.getCumulativePickQuantity());
                        response.setStorageYardAmount(Integer.toString(yard));
                    }
                }
            }

            response.setReceivedAmount(x.getArrivalQuantity() == null ? null : x.getDeliverQuantity().toString());
            response.setForecastOrderAmount(x.getSubtotalMoney() == null ? null : x.getSubtotalMoney().toString());
            response.setRepliedAmount(x.getExchangeAmt() == null ? null : x.getExchangeAmt().toString());
            response.setEffectiveDate(x.getTakeEffectTime());
            response.setInvalidDate(x.getInvalidDate());
            response.setExpectedDeliveryDate(x.getHopeDeliveryTime());
            response.setCreator(x.getCreator());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (x.getGmtCreate() != null) {
                response.setGmtCreate(format.format(x.getGmtCreate()));
            }
            if (x.getGmtModified() != null) {
                response.setGmtUpdate(format.format(x.getGmtModified()));
            }
            response.setUpdator(x.getUpdater());
            response.setRemark(x.getRemark());
            response.setLineRemark(x.getItemRemark());
            response.setIsClosed(x.getIsClosed() == null ? null : x.getIsClosed().toString());
            response.setRejectionReason(x.getCloseReason());
            response.setRejectionReasonName(x.getCloseReasonDescribe());
            response.setAllocateOrderCode(x.getAllocateOrderNo());
            response.setShipMethod(x.getShipMethod());
            response.setShipMethodName(x.getShipMethodName());
            if (StringUtils.isNotBlank(x.getOrderTag())) {
                response.setOrderTag(x.getOrderTag());
                response.setOrderTagName(orderTagMap.get(x.getOrderTag()));
            }
            if (StringUtils.isNotBlank(x.getBizUnit())) {
                response.setBizUnit(x.getBizUnit());
                response.setBizUnitName(bizUnitMap.get(x.getBizUnit()));
            }
            response.setMainBizFeatures(x.getMainBizFeature());
            response.setBizFeatures(x.getBizFeature());
            //单价
            response.setUnitPrice(x.getUnitPrice() == null ? null : x.getUnitPrice().toPlainString());

            return response;
        }).collect(Collectors.toList());
        Result<List<AllocateApplyOrderQueryResponse>> success = Result.success(responseList);
        success.setTotal(listResult.getTotal());
        return success;

    }

    @Override
    public Result<List<WarehouseInfo>> searchLogicWarehouse(SearchLogicWarehouseRequest searchLogicWarehouseRequest) {


        QueryCargoZoneRequest request = new QueryCargoZoneRequest();
        request.setCodes(searchLogicWarehouseRequest.getCodes());
        request.setBusinessType("11");
        request.setFromSys("APP_NYK");
        // request.setSapOrgCode(searchLogicWarehouseRequest.getSaleOrgCode());
        request.setModel(searchLogicWarehouseRequest.getModel());
        request.setType(searchLogicWarehouseRequest.getType() == null ? null : Integer.valueOf(searchLogicWarehouseRequest.getType()));
        request.setStatus(searchLogicWarehouseRequest.getStatus());
        request.setName(searchLogicWarehouseRequest.getName());
        request.setSize(searchLogicWarehouseRequest.getSize());
        com.alibaba.cz.base.tool.result.Result<ResultPager<List<CargoZoneSDO>>> result =
                cargoZoneQueryService.searchCargoZoneList(request);
        if (!result.isSuccess()) {
            return Result.fail(result.getErrorCode(), result.getMessage());
        }

        ResultPager<List<CargoZoneSDO>> listResult = result.getResult();
        if (listResult != null && CollectionUtils.isNotEmpty(listResult.getContent())) {
            List<CargoZoneSDO> content = listResult.getContent();
            List<WarehouseInfo> warehouseInfos = content.stream().map(cargoZoneSDO -> {
                WarehouseInfo warehouseInfo = new WarehouseInfo();
                warehouseInfo.setCode(cargoZoneSDO.getCode());
                warehouseInfo.setName(cargoZoneSDO.getName());
                warehouseInfo.setSapFactoryCode(cargoZoneSDO.getSapFactoryCode());
                Map<String, String> feature = cargoZoneSDO.getFeature();
                if (MapUtils.isNotEmpty(feature)) {
                    warehouseInfo.setSapSaleOrgCode(feature.get("sapOrgCode"));
                }
                warehouseInfo.setFeatures(cargoZoneSDO.getFeature());
                return warehouseInfo;
            }).collect(Collectors.toList());
            return Result.success(warehouseInfos);
        }
        return Result.success(new ArrayList<>());
    }
}
